class Solution {
public:
    int myAtoi(string s) {
        long long ret = 0;
        int cur = 0;
        int flag = 1;
        while(cur < s.size() && s[cur] == ' ')
        {
            cur++;
        }
        if(cur == s.size()) return 0;
        if(s[cur] == '-')
        {
            flag = -1;
            cur++;
        }
        else if (s[cur] == '+') {
            cur++;
        }
        else if(!isdigit(s[cur])) 
            return 0;
        for(; cur < s.size(); ++cur){
            char ch = s[cur];
            if(!isdigit(ch)) break;
            int tmp = flag * (ch - '0');
            long long check = ret * 10 + tmp;
            if (check >= INT_MAX) return INT_MAX;
            if (check <= INT_MIN) return INT_MIN;
            ret = check;
        }

        return (int)ret;
    }
};

// 错误提交
class Solution {
public:
    int myAtoi(string s) {
        int ret = 0;
        int flag = 1;
        for(auto ch : s){
            if((ch == '0' && ret == 0) || ch == ' '){
                // leading zero
                continue;
            }
            if(ch == '-'){
                flag = -1;
                continue;
            }
            if(!isdigit(ch)) break;  // not digit and space and minus
            int tmp = flag * (ch - '0');
            long long check = ret * 10 + tmp;
            if(check > INT_MAX || check < INT_MIN) return (int)check;
            ret = check;
        }

        return ret;
    }
};